<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


















  
  
    
  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.css">







<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=7.1.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=7.1.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="泛型概念泛型（ Generic）是一种编译器机制，您可通过该机制获取通用的代码并参数化（或模板化）剩余部分，从而以一种一般化方式创建（和使用）一些类型的实体（比如类或接口和方法）。这种编程方法被称为泛型编程。 所谓泛型，就是允许在定义类、接口、方法时使用类型形参，这个类型形参(或叫泛型)将在声明变量、创建对象、调用方法时动态地指定(即传入实际的类型参数，也可以称为「类型实参」)。">
<meta name="keywords" content="泛型,Generic">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 泛型知识笔记">
<meta property="og:url" content="https://michael728.github.io/2019/07/13/java-generic/index.html">
<meta property="og:site_name" content="Michael翔">
<meta property="og:description" content="泛型概念泛型（ Generic）是一种编译器机制，您可通过该机制获取通用的代码并参数化（或模板化）剩余部分，从而以一种一般化方式创建（和使用）一些类型的实体（比如类或接口和方法）。这种编程方法被称为泛型编程。 所谓泛型，就是允许在定义类、接口、方法时使用类型形参，这个类型形参(或叫泛型)将在声明变量、创建对象、调用方法时动态地指定(即传入实际的类型参数，也可以称为「类型实参」)。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://i.loli.net/2019/07/13/5d29407987abd35714.jpg">
<meta property="og:image" content="https://i.loli.net/2019/07/13/5d294c385b14039332.jpg">
<meta property="og:image" content="https://i.loli.net/2019/07/13/5d295bf0741a761687.jpg">
<meta property="og:image" content="https://i.loli.net/2019/07/13/5d2961d5155f246541.png">
<meta property="og:updated_time" content="2020-01-05T15:47:56.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java 泛型知识笔记">
<meta name="twitter:description" content="泛型概念泛型（ Generic）是一种编译器机制，您可通过该机制获取通用的代码并参数化（或模板化）剩余部分，从而以一种一般化方式创建（和使用）一些类型的实体（比如类或接口和方法）。这种编程方法被称为泛型编程。 所谓泛型，就是允许在定义类、接口、方法时使用类型形参，这个类型形参(或叫泛型)将在声明变量、创建对象、调用方法时动态地指定(即传入实际的类型参数，也可以称为「类型实参」)。">
<meta name="twitter:image" content="https://i.loli.net/2019/07/13/5d29407987abd35714.jpg">



  <link rel="alternate" href="/atom.xml" title="Michael翔" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://michael728.github.io/2019/07/13/java-generic/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Java 泛型知识笔记 | Michael翔</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1c9958c951d5a7661571422e0340e156";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <meta name="referrer" content="never">
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Michael翔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">因上努力，果上随缘！</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tools">

    
    
    
      
    

    

    <a href="/tools/" rel="section"><i class="menu-item-icon fa fa-fw fa-location-arrow"></i> <br>利器</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-books">

    
    
    
      
    

    

    <a href="/books" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i> <br>阅读</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-movies">

    
    
    
      
    

    

    <a href="/movies" rel="section"><i class="menu-item-icon fa fa-fw fa-film"></i> <br>观影</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-think">

    
    
    
      
    

    

    <a href="/think" rel="section"><i class="menu-item-icon fa fa-fw fa-lightbulb-o"></i> <br>一言</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://github.com/michael728" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://michael728.github.io/2019/07/13/java-generic/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Michael翔">
      <meta itemprop="description" content="DevOps CICD Blog 持续学习">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Michael翔">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Java 泛型知识笔记

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-13 12:49:10" itemprop="dateCreated datePublished" datetime="2019-07-13T12:49:10+00:00">2019-07-13</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2020-01-05 15:47:56" itemprop="dateModified" datetime="2020-01-05T15:47:56+00:00">2020-01-05</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="泛型概念"><a href="#泛型概念" class="headerlink" title="泛型概念"></a>泛型概念</h2><p>泛型（ <code>Generic</code>）是一种编译器机制，您可通过该机制获取通用的代码并参数化（或模板化）剩余部分，从而以一种一般化方式创建（和使用）一些类型的实体（比如类或接口和方法）。这种编程方法被称为泛型编程。</p>
<p>所谓泛型，就是允许在定义类、接口、方法时使用类型形参，这个类型形参(或叫泛型)将在声明变量、创建对象、调用方法时动态地指定(即传入实际的类型参数，也可以称为「类型实参」)。</p>
<a id="more"></a>
<p>JDK 5.0（2004 年发布）向 Java 语言中引入了泛型类型（泛型）和关联的语法。增加泛型支持，很大程度上都是为了让集合能记住其元素的数据类型。在没有泛型之前，一旦把一个对象「丢进」 Java 集合中，集合就会忘记对象的类型，把所有的对象当成 Object 类型处理。当程序从集合中取出对象后，就需要进行强制类型的转换。这种强制类型转换不仅使代码臃肿，还很容器引起 <code>ClassCastException</code> 错误。</p>
<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><p>先通过一个简单的示例了解一下泛型是什么样的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">List strList = <span class="keyword">new</span> ArrayList();</span><br><span class="line">strList.add(<span class="string">"Name"</span>);</span><br><span class="line">strList.add(<span class="string">"Aget"</span>);</span><br><span class="line"><span class="comment">// 不小心存入一个 Integer 对象</span></span><br><span class="line">strList.add(<span class="keyword">new</span> Integer(<span class="number">1</span>));</span><br><span class="line"><span class="comment">//ArrayList可以存放任意类型，所以，下一行执行，并不会报错</span></span><br><span class="line">System.out.println(strList);</span><br><span class="line"><span class="comment">//这一行强转就出错了</span></span><br><span class="line">String str = (String)strList.get(<span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[Name, Aget, <span class="number">1</span>]</span><br><span class="line">Exception in thread <span class="string">"main"</span> java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String</span><br><span class="line">	at main.main(main.java:<span class="number">14</span>)</span><br><span class="line"></span><br><span class="line">Process finished with exit code <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>可以看到，我们 在给 List 中元素包含了两种类型：String 和 Interger 类型。 在 JDK 5.0 之前，Java 语言对此行为没有任何约束，这导致了许多编码错误。因为不知道 List 中包含的内容，则必须检查想要访问的元素，查看是否能处理这种类型的元素，否则可能会遇到 <code>ClassCastException</code>。</p>
<p>借助泛型，可以事先指定 List 中的元素类型，这样编译器在编译阶段就能够发现上面的问题：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; strList = <span class="keyword">new</span> ArrayList();</span><br><span class="line">strList.add(<span class="string">"Name"</span>);</span><br><span class="line">strList.add(<span class="string">"Aget"</span>);</span><br><span class="line"><span class="comment">// 下面这一行编辑器就会提示错误，编译就不会通过</span></span><br><span class="line">strList.add(<span class="keyword">new</span> Integer(<span class="number">1</span>));</span><br><span class="line">System.out.println(strList);</span><br><span class="line">String str = (String)strList.get(<span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2019/07/13/5d29407987abd35714.jpg" alt="Jietu20190713-102223-listerror.jpg"></p>
<p>从 Java 5 之后，Java 引入了「参数化类型」(<code>parameterized type</code>)的概念。允许程序在创建集合时指定集合元素的类型。Java 的参数化类型被称为「泛型」(<code>Generic</code>)。</p>
<p>上面的 <code>List&lt;String&gt;</code>，可以称 List 是带一个类型参数的泛型接口，类型参数（类型实参）是 <code>Sting</code>。集合记住了所有元素的数据类型，从而无须对集合元素进行数据类型转换。</p>
<p>在 Java 7 之前，如果使用带有泛型的接口、类定义变量，那么调用构造器创建对象时，构造器的构面也要带上泛型：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; strList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br></pre></td></tr></table></figure>
<p>从  Java7 开始， Java 允许在构造器后不需要带完整的泛型信息，只需要给出尖括号即可，Java 可以自动推断出尖括号里的是什么泛型信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; strList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br></pre></td></tr></table></figure>
<h2 id="常见的-T，E，K，V，？"><a href="#常见的-T，E，K，V，？" class="headerlink" title="常见的 T，E，K，V，？"></a>常见的 T，E，K，V，？</h2><p>本质上这些个都是通配符，没啥区别，只不过是编码时的一种约定俗成的东西。比如上述代码中的 T ，我们可以换成 A-Z 之间的任何一个 字母都可以，并不会影响程序的正常运行，但是如果换成其他的字母代替 T ，在可读性上可能会弱一些。通常情况下，T，E，K，V，？ 是这样约定的：</p>
<ul>
<li>？ 表示不确定的 java 类型</li>
<li>T (type) 表示具体的一个java类型</li>
<li>K V (key value) 分别代表java键值中的Key Value</li>
<li>E (element) 代表Element</li>
</ul>
<h2 id="泛型的应用"><a href="#泛型的应用" class="headerlink" title="泛型的应用"></a>泛型的应用</h2><p>泛型有三种使用方式：</p>
<ol>
<li>泛型类</li>
<li>泛型接口</li>
<li>泛型方法</li>
</ol>
<h3 id="泛型类"><a href="#泛型类" class="headerlink" title="泛型类"></a>泛型类</h3><p>泛型类型用于类的定义中，这个类称为「泛型类」。最典型的泛型类就是各种容器类，例如：List、Set、Map。</p>
<p>泛型类的定义语法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> 类名称&lt;泛型标识&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">private</span> 泛型标识 成员变量；</span><br><span class="line">    ……</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>泛型标识：可以随便写任意标识号，标识指定的泛型的类型，比如常用的 <code>T</code></li>
</ul>
<p>举个栗子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 泛型类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Card</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T id;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(T id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Card</span><span class="params">(T id)</span></span>&#123;</span><br><span class="line">        setId(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// main 函数</span></span><br><span class="line">Card&lt;String&gt; card1 = <span class="keyword">new</span> Card&lt;&gt;(<span class="string">"One"</span>);</span><br><span class="line">System.out.println(<span class="string">"card1 id is: "</span>+card1.getId());</span><br><span class="line"></span><br><span class="line">Card&lt;Integer&gt; card2 = <span class="keyword">new</span> Card&lt;&gt;(<span class="number">2</span>);</span><br><span class="line">System.out.println(<span class="string">"card2 id is: "</span>+card2.getId());</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line">card1 id is: One</span><br><span class="line">card2 id is: <span class="number">2</span></span><br></pre></td></tr></table></figure>
<p>怎么样，看到区别了吗？同样一个类创建的两个实例，成员变量名都是 <code>id</code>，但是二者的类型却可以不同。<code>T</code> 感觉有种 <code>template</code> 的意思，模板嘛，占坑渲染即可。</p>
<p>定义的泛型类实例化对象时并不一定要春如泛型类型实参。比如一开始的例子 <code>ArrayList</code>，当不传入泛型类型实参时，默认的就是 <code>Object</code> 类型。这时候，就不会起到限制类型的作用了。</p>
<p>注意点：</p>
<ol>
<li>泛型的类型参数只能是「类类型」，不能是原始类型（<code>Primitive Type</code>）——byte/short/ int/long/float/ double/ boolean/char</li>
<li>定义泛型类中的构造器时，构造器名还是原来的类型，不需要增加泛型声明。</li>
<li>不能对确切的泛型类型使用 <code>instanceof</code>操作，比如 <code>card1 instanceof Card&lt;String&gt;</code>，会报 <code>instanceof 的泛型类型不合法</code> 错误，但是 <code>card1 instance Card</code> 是不会报错的，并返回 <code>true</code>。因为不管泛型的实际类型参数是什么，他们在运行时总有同样的类，对于 Java 来说，它们依然被当成同一个类处理，在内存中也只占用一块内存空间。</li>
</ol>
<p><code>List&lt;Integer&gt;</code> 并不是 <code>List&lt;Number&gt;</code> 的子类！<br><code>List&lt;Integer&gt;</code> 并不是 <code>List&lt;Number&gt;</code> 的子类！<br><code>List&lt;Integer&gt;</code> 并不是 <code>List&lt;Number&gt;</code> 的子类！</p>
<h3 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h3><p>泛型接口和泛型类的定义语法差不多。泛型接口经常被用在各种类的生成器中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义泛型接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Generaotr</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">next</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>泛型接口实现类，未传入泛型实参时：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FruitGenerator</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Generaotr</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 这个 Override 可不能少</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">next</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接口实现类定义时，也需要将泛型的声明加上。如果不加，例如<code>public class FruitGenerator implements Generaotr&lt;T&gt;</code>，这样就会报错，<code>cannot resolve symbol T</code>。</p>
<p>泛型接口实现类，传入泛型实参，比如 <code>String</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FruitGenerator</span> <span class="keyword">implements</span> <span class="title">Generaotr</span>&lt;<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String[] fruits = <span class="keyword">new</span> String[]&#123;<span class="string">"Apple"</span>, <span class="string">"Banana"</span>, <span class="string">"Pear"</span>&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">next</span><span class="params">()</span></span>&#123;</span><br><span class="line">        Random rand = <span class="keyword">new</span> Random();</span><br><span class="line">        <span class="keyword">return</span> fruits[rand.nextInt(<span class="number">3</span>)];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里我们传入了泛型实参，接口实现类中的泛型都改为了这个传入的实参。并且，此时，接口实行类就不用加上泛型声明了，加入的话，反而会提示 <code>attempting to use incompatible return type</code>错误。</p>
<h3 id="泛型通配符"><a href="#泛型通配符" class="headerlink" title="泛型通配符"></a>泛型通配符</h3><p><code>Integer</code> 是 <code>Number</code> 的一个子类。那么，在使用 <code>Card&lt;Numer&gt;</code> 作为方法形参的方法中，是否可以传入 <code>Card&lt;Interger&gt;</code> 的实参呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">showKeyValue1</span><span class="params">(Card&lt;Number&gt; card)</span></span>&#123;</span><br><span class="line">    System.out.println(card.getId());</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 测试</span></span><br><span class="line">Card&lt;Integer&gt; card2 = <span class="keyword">new</span> Card&lt;&gt;(<span class="number">2</span>);</span><br><span class="line">System.out.println(<span class="string">"card2 id is: "</span>+card2.getId());</span><br><span class="line"></span><br><span class="line">showKeyValue1(card2);</span><br></pre></td></tr></table></figure>
<p>编译器会报错 ：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Generic&lt;java.lang.Integer&gt; cannot be applied to Card&lt;java.lang.Number&gt;</span><br></pre></td></tr></table></figure>
<p>通过提示信息我们可以看到 <code>Card&lt;Integer&gt;</code> 不能被看作为 <code>Card&lt;Number&gt;</code> 的子类。</p>
<p>如何解决上面的问题呢？我们需要在逻辑上引入一个同时是 <code>Card&lt;Number&gt;</code> 和 <code>Card&lt;Interger</code> 父类的引用类型。由此，类型通配符产生了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 其实，这里不用通配符，直接是 Card 也会 OK</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">showKeyValue1</span><span class="params">(Card&lt;?&gt; card)</span></span>&#123;</span><br><span class="line">    System.out.println(card.getId());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>类型通配符一般是使用 <code>?</code> 代替具体的类型实参。注意，<code>?</code> 是类型实参，不是类型形参。简单理解，这里的 <code>?</code> 就和 <code>Number</code>、<code>String</code> 一样，都是一种实际的类型。可以把 <code>?</code> 看成所有类型的父亲，是一种真实的类型，当成 Object 来处理。</p>
<h4 id="通配符上界"><a href="#通配符上界" class="headerlink" title="通配符上界"></a>通配符上界</h4><p>为了表示限制类型，泛型提供了被限制的通配符。通配符上界使用 <code>&lt;? extends T&gt;</code> 的格式，意思是需要一个T类型或者T类型的子类，一般T类型都是一个具体的类型。示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">printIntValue</span><span class="params">(List&lt;? extends Number&gt; list)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (Number number : list) &#123;</span><br><span class="line">        System.out.print(number.intValue()+<span class="string">" "</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此处，未知类型一定是 <code>Number</code> 的子类型，因此，可以把 <code>Number</code> 称为这个通配符的上界(<code>upper bnound</code>)。</p>
<h4 id="通配符下界"><a href="#通配符下界" class="headerlink" title="通配符下界"></a>通配符下界</h4><p>除了可以指定通配符的上限之外，Java 还允许指定通配符的下限。通配符下界使用 <code>&lt;? super T&gt;</code> 的格式，意思是需要一个T类型或者 T 类型的父类，一般 T 类型都是一个具体的类型。示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fillNumberList</span><span class="params">(List&lt;? <span class="keyword">super</span> Number&gt; list)</span> </span>&#123;</span><br><span class="line">    list.add(<span class="keyword">new</span> Integer(<span class="number">0</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Float(<span class="number">1.0</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实，Java 泛型不仅允许在使用通配符形参时设定上限，还可以在定义泛型形参时设定上限，用以表示传给泛型形参的实际参数类型要么是该上限类型，要么是该上限类型的子类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Apple</span>&lt;<span class="title">T</span> <span class="keyword">extends</span> <span class="title">Number</span>&gt; </span>&#123;</span><br><span class="line">    T col;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Apple&lt;Integer&gt; ai = <span class="keyword">new</span> Apple&lt;&gt;();</span><br><span class="line">        Apple&lt;Double&gt; ad = <span class="keyword">new</span> Apple&lt;&gt;();</span><br><span class="line">        <span class="comment">// 下面编译就会出错，因为设置了上限是 Number</span></span><br><span class="line">        Apple&lt;String&gt; as = <span class="keyword">new</span> Apple&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2019/07/13/5d294c385b14039332.jpg" alt="Jietu20190713-111233-bound.jpg"></p>
<h3 id="泛型方法"><a href="#泛型方法" class="headerlink" title="泛型方法"></a>泛型方法</h3><p>在一些情况下，定义类、接口时没有使用泛型形参，但定义方法时想自己定义泛型形参，这也是可以的。Java 5 提供了对泛型方法的支持。</p>
<p>判断一个方法是否是泛型方法关键看方法返回值前面有没有使用 <code>&lt;&gt;</code> 标记的类型，有就是，没有就不是。</p>
<p>假设需要实现这样一个方法：将一个 Object 数组所有的元素天际到一个 Collection 集合中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">fromArrayToCollection</span><span class="params">(Object[] a, Collection&lt;Object&gt; c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (Object o : a) &#123;</span><br><span class="line">        c.add(o);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Collection&lt;String&gt;</code> 并不是 <code>Collection&lt;Object&gt;</code> 的子类型，所以上面这个方法只能将<br><code>Object[]</code> 数组中的元素复制到元素为 <code>Object</code>(<code>Object</code> 的子类也不行)的 Collection 集合中。所以，下面这么写将会引起编译错误：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">String[] strArr = &#123;<span class="string">"a"</span>,<span class="string">"b"</span>&#125;;</span><br><span class="line">List&lt;String&gt; strList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"><span class="comment">// Collection&lt;String&gt;对象不能当成 Collection&lt;Oject&gt;使用</span></span><br><span class="line">fromArrayToCollection(strArr,strList);</span><br><span class="line">System.out.println(strList);</span><br></pre></td></tr></table></figure>
<p><code>Collection&lt;Object&gt; c</code> 改为通配符 <code>Collection&lt;?&gt; c</code> 是否可行呢？也不行。</p>
<p>为了解决上面这个问题，可以使用泛型方法(<code>Generic Method</code>)。所谓泛型方法，就是在声明方法时，定义一个或多个泛型形参。多个泛型形参声明放在方法修饰符和方法返回值类型之间。泛型方法语法格式如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">修饰符 &lt;T,S,...&gt; 返回值类型 方法名(形参列表)&#123;</span><br><span class="line">    <span class="comment">// 方法体</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的方法改进如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">fromArrayToCollection</span><span class="params">(T[] a, Collection&lt;T&gt; c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (T o : a) &#123;</span><br><span class="line">        c.add(o);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>与泛型类和泛型接口的使用不同，泛型方法中的泛型形参不需要显示传入实际参数类型。编译器会根据实参推断泛型所代表的类型。但是小心，避免制造迷惑。比如下面的栗子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">		List&lt;String&gt; as = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        List&lt;Object&gt; ao = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 下面会编译错误</span></span><br><span class="line">        test(as, ao);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(Collection&lt;T&gt; from, Collection&lt;T&gt; to)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (T ele : from) &#123;</span><br><span class="line">            to.add(ele);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2019/07/13/5d295bf0741a761687.jpg" alt="Jietu20190713-121930-method-error.jpg"></p>
<p><code>test</code> 方法传入两个实参，<code>ao</code> 的数据类型是 <code>List&lt;Object&gt;</code>，而 <code>as</code> 的数据类型是 <code>List&lt;String&gt;</code>。与泛型方法签名进行对比，<code>test(Collection&lt;T&gt; from, Collection&lt;T&gt; to)</code>，编译器无法正确识别 T 所代表的实际类型。为了避免这种错误，可以改为如下形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(Collection&lt;? extends T&gt; from, Collection&lt;T&gt; to)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (T ele : from) &#123;</span><br><span class="line">        to.add(ele);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Collection&lt;? extends T&gt;</code>这种采用类型通配符并设置通配符上限的表示方式，只要 test 方法的第一个 Collection 集合里的元素类型是后一个 Collection 集合里元素类型的子类即可。</p>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><p>对于类中变量的类型，绘制了一个简单的图：</p>
<p><img src="https://i.loli.net/2019/07/13/5d2961d5155f246541.png" alt="变量"></p>
<p>作图工具：<a href="https://www.processon.com/i/55ddb6bae4b04fe84c504c5f" target="_blank" rel="noopener">ProcessOn</a>，强烈安利</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>经过上面的学习，我对泛型(<code>Generic</code>)有了初步的认识。类似于一个「模板」的概念，「占坑」等着渲染，提供了对类、接口、方法定义的灵活性，使用起来具有了「动态性」。当然，这只是我的个人理解，方便记忆的，可能表述并不是很准确。在实际的生产代码中，也有应用泛型类、泛型方法的，能够想到去使用它，无疑需要对泛型有比较好的理解。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://docs.oracle.com/javase/tutorial/java/generics/index.html" target="_blank" rel="noopener">Oracle-Generics Documentation</a></li>
<li><a href="https://blog.csdn.net/s10461/article/details/53941091" target="_blank" rel="noopener">CSDN-java 泛型详解-绝对是对泛型方法讲解最详细的，没有之一</a></li>
<li><a href="https://blog.csdn.net/ShuSheng0007/article/details/80720406#%E5%A6%82%E4%BD%95%E8%B0%83%E7%94%A8%E4%B8%80%E4%B8%AA%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95" target="_blank" rel="noopener">CSDN-ShuSheng007-秒懂Java泛型</a></li>
<li><a href="https://juejin.im/post/5b614848e51d45355d51f792" target="_blank" rel="noopener">掘金-深入理解Java泛型</a></li>
<li><a href="http://hinylover.space/2016/06/25/relearn-java-generic-1/" target="_blank" rel="noopener">重新认识Java——泛型（基础、使用和实现原理）</a></li>
<li><a href="http://www.glmapper.com/2019/08/19/base-java-generics/#%E5%B8%B8%E7%94%A8%E7%9A%84-T%EF%BC%8CE%EF%BC%8CK%EF%BC%8CV%EF%BC%8C%EF%BC%9F" target="_blank" rel="noopener">glmapper—聊一聊-JAVA 泛型中的通配符 T，E，K，V，？</a></li>
</ul>

      
    </div>

    
      

  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/25/it-basic-open-source-protocol/" rel="bookmark">IT 基础 —— 开源协议</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/07/java-spring-boot-hello-world/" rel="bookmark">Spring Boot 实战 —— 入门</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/10/java-spring-boot-log4j2/" rel="bookmark">Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/09/java-spring-boot-logback/" rel="bookmark">Spring Boot 实战 —— 日志框架 logback 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/20/java-spring-boot-mybatis/" rel="bookmark">Spring Boot 实战 —— MyBatis（注解版）使用方法</a></div>
      
    </li>
  
  </ul>


    

    
    
    

    
      <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center;">
  <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="Michael翔 wechat" style="width: 200px; max-width: 100%;">
  <div>欢迎订阅 ヾﾉ≧∀≦)o</div>
</div>

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>我知道是不会有人点的，但万一有人想不开呢👇</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Michael翔 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.png" alt="Michael翔 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Michael翔</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://michael728.github.io/2019/07/13/java-generic/" title="Java 泛型知识笔记">https://michael728.github.io/2019/07/13/java-generic/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/基础/" rel="tag"># 基础</a>
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/07/java-spring-boot-hello-world/" rel="next" title="Spring Boot 实战 —— 入门">
                <i class="fa fa-chevron-left"></i> Spring Boot 实战 —— 入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/14/java-spring-boot-swagger/" rel="prev" title="Spring Boot 实战 —— 集成 Swagger 生成 RESTful API 文档">
                Spring Boot 实战 —— 集成 Swagger 生成 RESTful API 文档 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yODgyMC81Mzkw" "></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo.jpg" alt="Michael翔">
            
              <p class="site-author-name" itemprop="name">Michael翔</p>
              <div class="site-description motion-element" itemprop="description">DevOps CICD Blog 持续学习</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">82</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">19</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">95</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/Michael728" title="GitHub &rarr; https://github.com/Michael728" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/1838446070/profile?topnav=1&wvr=6" title="微博 &rarr; https://weibo.com/1838446070/profile?topnav=1&wvr=6" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/michael-xiang/" title="博客园 &rarr; https://www.cnblogs.com/michael-xiang/" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.zhihu.com/people/michaelXoX" title="知乎 &rarr; https://www.zhihu.com/people/michaelXoX" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/728_michael" title="Twitter &rarr; https://twitter.com/728_michael" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://t.me/michaelxiang" title="Telegram &rarr; https://t.me/michaelxiang" rel="noopener" target="_blank"><i class="fa fa-fw fa-telegram"></i>Telegram</a>
                </span>
              
            </div>
          

          
             <div class="cc-license motion-element" itemprop="license">
              
              
                
              
              
              
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
             </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                关注列表
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2018/09/16/blog-interesting/" title="https://michael728.github.io/2018/09/16/blog-interesting/">Blog List</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://zcheng.ren/posts/" title="https://zcheng.ren/posts/" rel="noopener" target="_blank">ZeeCoder</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ehlxr.me/" title="https://ehlxr.me/" rel="noopener" target="_blank">ehlxr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.kawabangga.com/" title="https://www.kawabangga.com/" rel="noopener" target="_blank">卡瓦邦噶-蚂蚁SRE</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.stdioa.com/" title="https://blog.stdioa.com/" rel="noopener" target="_blank">David Dai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bestzuo.cn/" title="https://bestzuo.cn/" rel="noopener" target="_blank">Sanarous</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhyong.cn/" title="https://www.zhyong.cn/" rel="noopener" target="_blank">ZhangYong-爱折腾软件</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.dalaoyang.cn/" title="https://www.dalaoyang.cn/" rel="noopener" target="_blank">Dalaoyang-SpringBoot</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wuliaole.com/index.html" title="http://www.wuliaole.com/index.html" rel="noopener" target="_blank">无聊小博</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ilovey.live/" title="http://ilovey.live/" rel="noopener" target="_blank">低调小熊猫-Java开发</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2016/09/03/blog-logfile/" title="https://michael728.github.io/2016/09/03/blog-logfile/">建站日志</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型概念"><span class="nav-number">1.</span> <span class="nav-text">泛型概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例"><span class="nav-number">2.</span> <span class="nav-text">示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见的-T，E，K，V，？"><span class="nav-number">3.</span> <span class="nav-text">常见的 T，E，K，V，？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型的应用"><span class="nav-number">4.</span> <span class="nav-text">泛型的应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型类"><span class="nav-number">4.1.</span> <span class="nav-text">泛型类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型接口"><span class="nav-number">4.2.</span> <span class="nav-text">泛型接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型通配符"><span class="nav-number">4.3.</span> <span class="nav-text">泛型通配符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#通配符上界"><span class="nav-number">4.3.1.</span> <span class="nav-text">通配符上界</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通配符下界"><span class="nav-number">4.3.2.</span> <span class="nav-text">通配符下界</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型方法"><span class="nav-number">4.4.</span> <span class="nav-text">泛型方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#补充"><span class="nav-number">5.</span> <span class="nav-text">补充</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Michael翔</span>

  

  
</div>









        








        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
      
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest.min.js"></script>













  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js"></script>


  


  <script src="/js/utils.js?v=7.1.1"></script>

  <script src="/js/motion.js?v=7.1.1"></script>



  
  


  <script src="/js/affix.js?v=7.1.1"></script>

  <script src="/js/schemes/pisces.js?v=7.1.1"></script>




  
  <script src="/js/scrollspy.js?v=7.1.1"></script>
<script src="/js/post-details.js?v=7.1.1"></script>



  


  <script src="/js/next-boot.js?v=7.1.1"></script>


  

  

  

  


  
    <script>
  window.livereOptions = {
    refer: '2019/07/13/java-generic/'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
